#include <sys/time.h>
#include <osip2/osip.h>
#include <netinet/ip.h>
#include <netinet/udp.h>
#include <netinet/tcp.h>
#include "sip-client.h"
#include "sip-server-cfg.h"

sip_client::sip_client()
{

}

sip_client::~sip_client()
{

}


bool sip_client::server_start_platform()
{
    std::string str_sip_id("");
    std::string str_sip_domain("");
    std::string str_sip_host("");
    unsigned short us_sip_port = 0;
    std::string str_sip_password("");
    singleton_lock_sip_server_cfg_handler::Instance()->get_sip_server_cfg(str_sip_id, str_sip_domain, str_sip_host, us_sip_port, str_sip_password);

    if(mp_ectx_platform != nullptr){
        return false;
    }

    mp_ectx_platform = eXosip_malloc();
    int i_ret = eXosip_init(mp_ectx_platform);
    if(i_ret != OSIP_SUCCESS){
        printf("eXosip_init failed, return false!\n");
        return false;
    }

    i_ret = eXosip_listen_addr(mp_ectx_platform, IPPROTO_UDP, NULL, us_sip_port + 1, AF_INET, 0);
    if(i_ret != OSIP_SUCCESS){
        printf("eXosip_listen_addr failed.\n");
        return false;
    }

    mpt_event_thread = new std::thread(&sip_client::hk_eXosip_processEvent_superior_platform, this);

    return true;
}

void sip_client::hk_eXosip_processEvent_superior_platform()
{
    std::string str_sip_id("");
    std::string str_sip_domain("");
    singleton_lock_sip_server_cfg_handler::Instance()->get_sip_server_sip_info(str_sip_id, str_sip_domain);


    eXosip_event_t *p_event = NULL;  // msg event
    osip_message_t *p_answer = NULL; // ack

    while(!mb_thread_fini){
        p_event = eXosip_event_wait( mp_ectx_platform, 0, 200 );

        eXosip_lock( mp_ectx_platform );
        eXosip_default_action( mp_ectx_platform, p_event );
        eXosip_automatic_action( mp_ectx_platform );
        eXosip_unlock( mp_ectx_platform );

        if(p_event == nullptr){
            osip_usleep( 10000 );
            continue;
        }

        switch(p_event->type){
        case EXOSIP_REGISTRATION_SUCCESS:
        {
            //向上级注册成功,此处暂时不做
            break;
        }
        case EXOSIP_REGISTRATION_FAILURE:
        {
            //向上级注册失败,此处暂时不做
            break;
        }
        case EXOSIP_MESSAGE_NEW:
        {
            //接收到新消息
            break;
        }
        default:
            break;
        }
    }
}

